import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This class will let user to register.
// It will check to see if the user id already exists or not
public class RegisterPage extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
	response.setContentType("text/html");
	PrintWriter pw = response.getWriter();
	String userId = request.getParameter("userId");
	String firstName = request.getParameter("firstName");
	String lastName = request.getParameter("lastName");
	String password = request.getParameter("password");

	//connect to the database
	Connection con = null;
	PreparedStatement pst = null;
	ResultSet rs = null;
	Statement stmt = null;
	String query = "";
	try {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
	con = DriverManager.getConnection("jdbc:mysql://bungle08.cs.toronto.edu:3306/group22",
			"group22", "123456");
		if(!con.isClosed()){
		
			// check to susee if the user exists already (ie, userId exists)
			query = "SELECT id from user where id = \""+userId+"\"";
			stmt = con.createStatement();		
			rs = stmt.executeQuery(query);	
			
			if(!rs.next()){			
				// If not, add the user to the database
				query = "INSERT INTO user (id, first_name, last_name, password) values (?,?,?,?)";		
				pst = con.prepareStatement(query);
				pst.setString(1,userId);
				pst.setString(2,firstName);
				pst.setString(3,lastName);
				pst.setString(4,password);

				int i = pst.executeUpdate();
				if(i!=0){
					pw.println("1");
				}			
			}else{
				// If the user exists already, send message "0" back.
				pw.println("0");
			}
		}
	}
	 catch(Exception e) {
		pw.println("Exception: " + e.getMessage());
	} finally {
		try {
			if(con != null)
				con.close();
		} catch(SQLException e) {}
	}}
}
					